﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// Summary description for CProduct
/// </summary>
public class CProduct
{
	public CProduct()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public bool Add(string title,int parent,string isclass,string content)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("Parent", parent);
        object obj = d.ExeScalar("select count(*) from product where parent=@Parent", pars);
        pars.Add("Title", title);
        pars.Add("SortCode", Convert.ToInt32(obj) + 1);
        pars.Add("IsClass", isclass);
        pars.Add("Content", content);
        int c = d.ExeNonQuery("insert into product(parent,title,sortcode,isclass,content) values(@Parent,@Title,@SortCode,@IsClass,@Content)", pars);
        d.Close();
        if (c > 0)
        {
            return true;
        }
        return false;
    }

    public bool Delete(int id)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("ID", id);
        DataTable dt = d.ExeDataTable("select * from product where ID=@ID", pars);
        int c = d.ExeNonQuery("delete from product where id=@ID", pars);
        pars.Clear();
        pars.Add("Parent",Convert.ToInt32( dt.Rows[0]["parent"].ToString()));
        pars.Add("SortCode", Convert.ToInt32(dt.Rows[0]["SortCode"].ToString()));
        c += d.ExeNonQuery("update product set sortcode=sortcode-1 where parent=@Parent and sortcode > @SortCode", pars);
        d.Close();
        if (c>0)
        {
            return true;
        }
        return false;
    }

    public bool Update(int id,string title,string content)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("Title", title);
        pars.Add("Content", content);
        pars.Add("ID", id);
        int c = d.ExeNonQuery("update product set title=@Title,content=@Content where id=@ID", pars);
        d.Close();
        if (c> 0)
        {
            return true;
        }
        return false;
    }

    public bool SetImage(int id,string path,Page p)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("ID", id);
        DataTable dt = d.ExeDataTable("select * from product where ID=@ID", pars);
        if (null != dt && dt.Rows[0]["image"].ToString() != "")
        {
            try
            {
                if (System.IO.File.Exists(p.Server.MapPath("~/" + dt.Rows[0]["image"].ToString())))
                {
                    System.IO.File.Delete(p.Server.MapPath("~/" + dt.Rows[0]["image"].ToString()));
                }
            }
            catch (Exception)
            { }
        }
        
        pars.Clear();
        pars.Add("Path", path);
        pars.Add("ID", id);
        int c = d.ExeNonQuery("update product set [image]=@Path where id=@ID", pars);
        d.Close();
        if (c>0)
        {
            return true;
        }
        return false;
    }

    public DataTable ReadProducts(int parent)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("Parent", parent);
        DataTable dt = d.ExeDataTable("select * from product where parent=@Parent and isclass='0' order by sortcode asc", pars);
        d.Close();
        return dt;
    }

    public DataTable ReadCategories(int parent)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("Parent", parent);
        DataTable dt = d.ExeDataTable("select * from product where parent=@Parent and isclass='1' order by sortcode asc", pars);
        d.Close();
        return dt;
    }

    public DataRow Read(int id)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("ID", id);
        DataTable dt = d.ExeDataTable("select * from product where ID=@ID", pars);
        d.Close();
        if (null != dt)
        {
            return dt.Rows[0];
        }
        return null;
    }

    public bool Sort(int id, bool isUp)
    {
        DataAccess d = new DataAccess();
        d.Open();
        Dictionary<object, object> pars = new Dictionary<object, object>();
        pars.Add("ID", id);
        DataTable dt = d.ExeDataTable("select * from product where id=@ID", pars);
        pars.Clear();
        pars.Add("Parent", Convert.ToInt32(dt.Rows[0]["parent"].ToString()));
        pars.Add("SortCode", Convert.ToInt32(dt.Rows[0]["sortcode"].ToString()));
        if (isUp)
        {
            dt = d.ExeDataTable("select top 1 * from product where  parent=@Parent and sortcode<@SortCode order by sortcode desc", pars);
        }
        else
        {
            dt = d.ExeDataTable("select top 1 * from product where  parent=@Parent and sortcode >@SortCode order by sortcode asc", pars);
        }
        pars.Clear();
        pars.Add("ID", id);
        int c = d.ExeNonQuery("update product set sortcode=" + (isUp ? "sortcode-1" : "sortcode+1") + " where id=@ID", pars);
        pars.Clear();
        if (null != dt)
        {
            pars.Add("ID", Convert.ToInt32(dt.Rows[0]["id"].ToString()));
            c += d.ExeNonQuery("update product set sortcode=" + (isUp ? "sortcode+1" : "sortcode-1") + " where id=@ID", pars);
        }
        d.Close();
        if (c > 0)
        {
            return true;
        }
        d.Close();
        return false;
    }

    public ProductInfo[] ReadCategoryTree(int parent)
    {
        DataTable dt = ReadCategories(parent);
        if (null != dt)
        {
            ProductInfo[] infos = new ProductInfo[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ProductInfo info = new ProductInfo()
                {
                    ID = Convert.ToInt32(dt.Rows[i]["id"].ToString()),
                    Title = dt.Rows[i]["title"].ToString(),
                    Parent = Convert.ToInt32(dt.Rows[i]["parent"].ToString()),
                    Image = dt.Rows[i]["image"].ToString(),
                    Content = dt.Rows[i]["content"].ToString()
                };

                #region Children
                info.Children = ReadCategoryTree(info.ID);
                #endregion

                infos[i] = info;
            }
            return infos;
        }
        return null;
    }

    public ProductInfo[] ReadProductTree(int parent)
    {
        List<ProductInfo> lst = new List<ProductInfo>();
        DataTable dt = ReadProducts(parent);
        if (null != dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ProductInfo info = new ProductInfo()
                {
                    ID = Convert.ToInt32(dt.Rows[i]["id"].ToString()),
                    Title = dt.Rows[i]["title"].ToString(),
                    Parent = Convert.ToInt32(dt.Rows[i]["parent"].ToString()),
                    Image = dt.Rows[i]["image"].ToString(),
                    Content = dt.Rows[i]["content"].ToString()
                };

                lst.Add(info);
            }
        }

        //子分类产品
        dt = ReadCategories(parent);
        if (null != dt)
        {
            foreach (DataRow r in dt.Rows)
            {
                lst.AddRange(ReadProductTree(Convert.ToInt32(r["id"].ToString())));
            }
        }
        return lst.ToArray();
    }

    public List<string[]> GetProductPath(int id)
    {
        List<string[]> lst = new List<string[]>();
        DataRow r = Read(id);
        lst.Add(new string[] { r["id"].ToString(), r["title"].ToString() });
        if (r["parent"].ToString() != "0")
        {
            lst.InsertRange(0, GetProductPath(Convert.ToInt32(r["parent"].ToString())));
        }
        return lst;
    }
}